/******************************************************************************
 * Copyright (C) 2015  671643387@qq.com
 *
 * This program is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License as published by the
 * Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
 * more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, write to the Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
 *
 *****************************************************************************/

#include "AtExit.h"
#include <cassert>
#include "UGame/System/LockGuard.h"
using UGame::System::LockGuard;
using UGame::System::Mutex;

namespace UGame {

    AtExit* AtExit::_sInst = NULL;

    AtExit::AtExit(void)
        : _exitFuncs()
        , _mutex()
    {
        UASSERT(_sInst == NULL);
        _sInst = this;
    }

    AtExit::~AtExit(void)
    {
        while (!_exitFuncs.empty()) {
            _exitFuncs.top()();
            _exitFuncs.pop();
        }
    }

    void AtExit::Push(ATEXIT_FUNC _Callback)
    {
        UASSERT(_sInst != NULL);
        UMUTEX_LOCK_ASSERT(_Guard, _sInst->_mutex);
        _sInst->_exitFuncs.push(_Callback);
    }
}